package com.logictech.lims.web.back;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.velocity.VelocityContext;
import org.jeecgframework.p3.core.common.utils.AjaxJson;
import org.jeecgframework.p3.core.util.SystemTools;
import org.jeecgframework.p3.core.util.plugin.ContextHolderUtils;
import org.jeecgframework.p3.core.util.plugin.ViewVelocity;
import org.jeecgframework.p3.core.utils.common.PageQuery;
import org.jeecgframework.p3.core.web.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.logictech.activity.system.dao.SystemUserDao;
import com.logictech.activity.system.entity.SystemUser;
import com.logictech.activity.system.service.SystemUserService;
import com.logictech.activity.system.vo.LoginUser;
import com.logictech.common.util.data.DateUtils;
import com.logictech.common.util.data.ExcelUtil;
import com.logictech.common.util.data.StringUtils;
import com.logictech.lims.dto.ReagentInventoryDto;
import com.logictech.lims.entity.ReagentInventory;
import com.logictech.lims.service.LogService;
import com.logictech.lims.service.ReagentInventoryService;
import com.logictech.wechat.model.responseDto.JsonResp;

/**
 * 描述：</b>ReagentInventoryController<br>
 * 
 * @author guoqi
 * @since：2017年03月21日 16时10分44秒 星期二
 * @version:1.0
 */
@Controller
@RequestMapping("/lims/back/reagentInventory")
public class ReagentInventoryController extends BaseController {
	@Autowired
	private ReagentInventoryService reagentInventoryService;
	
	@Autowired
	private SystemUserService systemUserService;
	
	@Autowired
	private SystemUserDao systemUserDao;
	
	@Autowired
	private LogService logService;

	/**
	 * 列表页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "list", method = { RequestMethod.GET, RequestMethod.POST })
	public void list(@ModelAttribute ReagentInventoryDto query, HttpServletResponse response, HttpServletRequest request,
			@RequestParam(required = false, value = "pageNo", defaultValue = "1") int pageNo,
			@RequestParam(required = false, value = "pageSize", defaultValue = "10") int pageSize) throws Exception {
		PageQuery<ReagentInventoryDto> pageQuery = new PageQuery<ReagentInventoryDto>();
		pageQuery.setPageNo(pageNo);
		pageQuery.setPageSize(pageSize);
		VelocityContext velocityContext = new VelocityContext();
		pageQuery.setQuery(query);
		velocityContext.put("reagentInventory", query);
		velocityContext.put("pageInfos",
				SystemTools.convertPaginatedList(reagentInventoryService.queryPageList(pageQuery)));
		String viewName = "lims/back/reagentInventory-list.vm";
		request.getSession().setAttribute("pageQueryReagentInventoryDto", pageQuery);
		ViewVelocity.view(request, response, viewName, velocityContext);
	}
	
	/**
	 * 返回列表页面
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "back", method = { RequestMethod.GET, RequestMethod.POST })
	public void back(@ModelAttribute ReagentInventoryDto query, HttpServletResponse response, HttpServletRequest request,
			@RequestParam(required = false, value = "pageNo", defaultValue = "1") int pageNo,
			@RequestParam(required = false, value = "pageSize", defaultValue = "10") int pageSize) throws Exception {
		PageQuery<ReagentInventoryDto> pageQuery = new PageQuery<ReagentInventoryDto>();
		Object session = request.getSession().getAttribute("pageQueryReagentInventoryDto");
		if(session != null){
			pageQuery = (PageQuery<ReagentInventoryDto>)session;
			query = pageQuery.getQuery();
		}else{
			pageQuery.setPageNo(pageNo);
			pageQuery.setPageSize(pageSize);
			pageQuery.setQuery(query);
		}
		
		VelocityContext velocityContext = new VelocityContext();
		velocityContext.put("reagentInventory", query);
		velocityContext.put("pageInfos",
				SystemTools.convertPaginatedList(reagentInventoryService.queryPageList(pageQuery)));
		String viewName = "lims/back/reagentInventory-list.vm";
		ViewVelocity.view(request, response, viewName, velocityContext);
	}
	
	/**
	 * 导出excel
	 * 
	 * @return
	 */
	@RequestMapping(value = "export", method = { RequestMethod.GET, RequestMethod.POST })
	public void export(@ModelAttribute ReagentInventoryDto query, HttpServletResponse response, HttpServletRequest request) throws Exception {
		try{
			LoginUser user = (LoginUser) ContextHolderUtils.getSession().getAttribute("OPERATE_WEB_LOGIN_USER");
			logService.doAdd(user.getUserName() + "导出试剂库存信息");
			
			PageQuery<ReagentInventoryDto> pageQuery = new PageQuery<ReagentInventoryDto>();
			pageQuery.setQuery(query);
			List<ReagentInventoryDto> reagentInventoryDtoList = reagentInventoryService.queryList(pageQuery);
			LinkedHashMap<String, String> fieldMap = new LinkedHashMap<String, String>();
			fieldMap.put("barCode", "条形码编号");
			fieldMap.put("reagentType", "试剂名称");
			fieldMap.put("batchNo", "批号");
			fieldMap.put("receivedDate", "接收日期");
			fieldMap.put("opener", "开启人");
			fieldMap.put("openDate", "开启日期");
			fieldMap.put("effectiveDate", "有效日期");
			fieldMap.put("status", "状态");
			ExcelUtil.listToExcel(reagentInventoryDtoList, fieldMap, "试剂库存信息", 65535, response);
		}catch(Exception e){
			System.out.println(e.getStackTrace());
		}
	}

	/**
	 * 详情
	 * 
	 * @return
	 */
	@RequestMapping(value = "toDetail", method = RequestMethod.GET)
	public void toDetail(@RequestParam(required = true, value = "id") String id,
			HttpServletResponse response, HttpServletRequest request) throws Exception {
		VelocityContext velocityContext = new VelocityContext();
		String viewName = "lims/back/reagentInventory-detail.vm";
		ReagentInventory reagentInventory = reagentInventoryService.queryById(id);
		velocityContext.put("reagentInventory", reagentInventory);
		ViewVelocity.view(request, response, viewName, velocityContext);
	}

	/**
	 * 跳转到添加页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/toAdd", method = { RequestMethod.GET, RequestMethod.POST })
	public void toAdd(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws Exception {
		VelocityContext velocityContext = new VelocityContext();
		List<SystemUser> userList = systemUserService.queryNormalList();
		velocityContext.put("userList", userList);
		String viewName = "lims/back/reagentInventory-add.vm";
		ViewVelocity.view(request, response, viewName, velocityContext);
	}

	/**
	 * 保存信息
	 * 
	 * @return
	 */
	@RequestMapping(value = "/doAdd", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public AjaxJson doAdd(@ModelAttribute ReagentInventoryDto reagentInventory) {
		AjaxJson j = new AjaxJson();
		try {
			LoginUser user = (LoginUser) ContextHolderUtils.getSession().getAttribute("OPERATE_WEB_LOGIN_USER");
			reagentInventory.setCreateUser(user.getId().toString());
			reagentInventory.setCreateTime(new Date());
			reagentInventory.setUpdateUser(user.getId().toString());
			reagentInventory.setUpdateTime(new Date());
			
			if(!StringUtils.isEmpty(reagentInventory.getOpener())){
				String openerVal = systemUserDao.get(reagentInventory.getOpener()).getUserName();
				reagentInventory.setOpenerVal(openerVal);
			}
			
			// 编号规则 01:试剂 02：试液
			String type = "01";
			String year = DateUtils.formatString(new Date(), "yyyyMMdd");
			// 查询db中的最大编号
			int maxNo = reagentInventoryService.getMaxNo(type+year);
			Integer num = reagentInventory.getNum();
			
			if(num == null || num==1){
				maxNo++;
				String barCode = type+year+String.format("%04d", maxNo);
				reagentInventory.setBarCode(barCode);
				reagentInventoryService.doAdd(reagentInventory);
			}else{
				for(int i=0;i<num;i++){
					maxNo++;
					String barCode = type+year+String.format("%04d", maxNo);
					reagentInventory.setBarCode(barCode);
					reagentInventoryService.doAdd(reagentInventory);
				}
			}
			j.setMsg("保存成功");
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("保存失败");
		}
		return j;
	}

	/**
	 * 跳转到编辑页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "toEdit", method = RequestMethod.GET)
	public void toEdit(@RequestParam(required = true, value = "id") String id, HttpServletResponse response,
			HttpServletRequest request) throws Exception {
		VelocityContext velocityContext = new VelocityContext();
		ReagentInventoryDto reagentInventory = reagentInventoryService.queryById(id);
		velocityContext.put("reagentInventory", reagentInventory);
		List<SystemUser> userList = systemUserService.queryAllList();
		velocityContext.put("userList", userList);
		String viewName = "lims/back/reagentInventory-edit.vm";
		ViewVelocity.view(request, response, viewName, velocityContext);
	}

	/**
	 * 编辑
	 * 
	 * @return
	 */
	@RequestMapping(value = "/doEdit", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public AjaxJson doEdit(@ModelAttribute ReagentInventory reagentInventory) {
		AjaxJson j = new AjaxJson();
		try {
			LoginUser user = (LoginUser) ContextHolderUtils.getSession().getAttribute("OPERATE_WEB_LOGIN_USER");
			reagentInventory.setUpdateUser(user.getId().toString());
			reagentInventory.setUpdateTime(new Date());
			
			if(!StringUtils.isEmpty(reagentInventory.getOpener())){
				String openerVal = systemUserDao.get(reagentInventory.getOpener()).getUserName();
				reagentInventory.setOpenerVal(openerVal);
			}
			
			reagentInventoryService.doEdit(reagentInventory);
			j.setMsg("编辑成功");
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("编辑失败");
		}
		return j;
	}

	/**
	 * 删除
	 * 
	 * @return
	 */
	@RequestMapping(value = "doDelete", method = RequestMethod.GET)
	@ResponseBody
	public AjaxJson doDelete(@RequestParam(required = true, value = "id") String id) {
		AjaxJson j = new AjaxJson();
		try {
			reagentInventoryService.doDelete(id);
			j.setMsg("删除成功");
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("删除失败");
		}
		return j;
	}
	
	/**
	 * 打印
	 * 
	 * @return
	 */
	@RequestMapping(value = "doPrint", method = RequestMethod.GET)
	@ResponseBody
	public AjaxJson doPrint(@RequestParam(required = true, value = "id") String id) {
		AjaxJson j = new AjaxJson();
		try {
			// 开始打印试剂
			this.reagentInventoryService.startPrint(reagentInventoryService.queryById(id).getBarCode());
			j.setMsg("");
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("打印失败");
		}
		return j;
	}
	
	/**
	 * 打印完成，更新打印状态
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = { "/finishPrint" }, produces = "application/json",method = { org.springframework.web.bind.annotation.RequestMethod.GET,
			org.springframework.web.bind.annotation.RequestMethod.POST })
	@ResponseBody
    public JsonResp<String> finishPrint(@RequestParam(required = true, value = "barCode") String barCode){
		
		// 试剂打印完成
		this.reagentInventoryService.finishPrint(barCode);
        this.logService.doAdd("打印试剂标签完成，编号：" + barCode);
        return new JsonResp<String>();
    }
}
